import enum
import json
import uuid
from loguru import logger

# ======== 枚举 ======== #
class EventType(enum.Enum):
    Search = "search"
    Start = "start"
    Stop = "stop"
    Reset = "reset"  # 重置浏览器（删除user_data全新启动）
    Login = "login"
    Status = "status"
    Heartbeat = "heartbeat"
    Error = "error"
    Order = "order"
    OrderCancel = "cancel_order"
    GetAddress = "get_address"  # 获取收货地址列表
    UpdateSellerBlacklist = "update_seller_blacklist"  # ✅ 更新卖家黑名单
    UpdateTitleBlacklist = "update_title_blacklist"  # ✅ 更新标题黑名单
    ChatOpen = "chat_open"
    ChatSend = "chat_send"
    ChatSendImage = "chat_send_image"  # ✅ 发送图片消息
    ChatUploadImage = "chat_upload_image"  # ✅ 上传图片（使用Agent的Cookie和IP）
    ChatRead = "chat_read"  # ✅ 已读回执
    ChatRecall = "chat_recall"  # ✅ 撤回消息
    ChatMessage = "chat_message"
    MessageEvent = "message_event"  # ✅ 消息状态机事件（message_created, message_confirmed, message_failed等）
    LoadEmoji = "load_emoji_list"  # ✅ 加载表情包列表
    Unknown = "unknown"

class EventDirection(enum.Enum):
    Request = "req"
    Response = "res"

# ======== AttrDict ======== #
class AttrDict(dict):
    """支持 data.xxx 访问"""
    def __getattr__(self, name):
        return self.get(name)
    def __setattr__(self, name, value):
        self[name] = value

# ======== CommandEvent ======== #
class CommandEvent:
    def __init__(
        self,
        event: EventType,
        direction: EventDirection = EventDirection.Response,
        success: bool = True,
        code: int = 0,
        msg: str = "",
        data=None,
        req_id=None
    ):
        self.event: EventType = event
        self.direction: EventDirection = direction
        self.success: bool = success
        self.code: int = code
        self.msg: str = msg
        self.data: AttrDict = AttrDict(data or {})
        self.req_id: str = req_id or str(uuid.uuid4())

    # ======== 链式构建结果 ======== #
    def Success(self, data=None, msg="", code=0):
        self.success = True
        self.code = code
        if msg:
            self.msg = msg
        if data is not None:
            self.data = AttrDict(data)
        return self.to_dict()

    def Fail(self, msg="", data=None, code=1):
        self.success = False
        self.code = code
        self.msg = msg
        if data is not None:
            self.data = AttrDict(data)
        return self.to_dict()

    # ======== 转字典/JSON ======== #
    def to_dict(self):
        return {
            "event": self.event.value,
            "direction": self.direction.value,
            "success": self.success,
            "code": self.code,
            "msg": self.msg,
            "data": dict(self.data),
            "req_id": self.req_id
        }

    def to_json(self):
        return json.dumps(self.to_dict(), ensure_ascii=False)

    # ======== 解析接收到的原始数据 ======== #
    @classmethod
    def parse(cls, raw: str):
        try:
            d = json.loads(raw)
            event_str = d.get("event", "unknown")
            
            # ✅ 修复：如果事件类型不存在，使用Unknown
            try:
                event = EventType(event_str)
            except ValueError:
                logger.warning(f"⚠️ 未知事件类型: {event_str}，使用Unknown")
                event = EventType.Unknown
            
            direction = EventDirection(d.get("direction", "req"))
            return cls(
                event=event,
                direction=direction,
                success=d.get("success", True),
                code=d.get("code", 0),
                msg=d.get("msg", ""),
                data=d.get("data", {}),
                req_id=d.get("req_id")
            )
        except Exception as e:
            logger.warning(f"[解析失败] {raw}, error: {e}")
            return None

# ======== 工厂方法，方便快速生成事件 ======== #
class CommandRes:
    Search = lambda: CommandEvent(EventType.Search)
    Login = lambda: CommandEvent(EventType.Login)
    Order = lambda: CommandEvent(EventType.Order)
    OrderCancel = lambda: CommandEvent(EventType.OrderCancel)
    Start = lambda: CommandEvent(EventType.Start)
    Stop = lambda: CommandEvent(EventType.Stop)
    Reset = lambda: CommandEvent(EventType.Reset)
    Status = lambda: CommandEvent(EventType.Status)
    Heartbeat = lambda: CommandEvent(EventType.Heartbeat)
    Error = lambda: CommandEvent(EventType.Error)
    GetAddress = lambda: CommandEvent(EventType.GetAddress)
    ChatOpen = lambda: CommandEvent(EventType.ChatOpen)
    ChatSend = lambda: CommandEvent(EventType.ChatSend)
    ChatSendImage = lambda: CommandEvent(EventType.ChatSendImage)  # ✅ 发送图片消息
    ChatUploadImage = lambda: CommandEvent(EventType.ChatUploadImage)  # ✅ 上传图片
    ChatRead = lambda: CommandEvent(EventType.ChatRead)  # ✅ 已读回执
    ChatRecall = lambda: CommandEvent(EventType.ChatRecall)  # ✅ 撤回消息
    ChatMessage = lambda: CommandEvent(EventType.ChatMessage)
    MessageEvent = lambda: CommandEvent(EventType.MessageEvent)  # ✅ 消息状态机事件
    LoadEmoji = lambda: CommandEvent(EventType.LoadEmoji)  # ✅ 加载表情包
